package com.senven.common.user.service.impl;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.senven.common.entity.User;
import com.senven.common.user.config.PasswordConfig;
import com.senven.common.user.feign.RoleFeign;
import com.senven.common.user.mapper.UserMapper;
import com.senven.common.user.service.UserService;
import com.senven.common.user.vo.UserVo;
import com.senven.common.vo.CommonResult;
import org.apache.commons.collections.Factory;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.SocketUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class implUserService implements UserService {
    @Autowired
    private RoleFeign roleFeign;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;
    @Override
    public User findUserByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        wrapper.eq("is_deleted",0);
        User user = userMapper.selectOne(wrapper);
        return user;
    }

    @Override
    public CommonResult findInfo(Integer currentPage,Integer pageSize, UserVo userVo) {
        Page<User> page= new Page<>(currentPage,pageSize);
        QueryWrapper<User> wrapper = new QueryWrapper();

        if(StringUtils.hasText(userVo.getRealname())){
            wrapper.like("realname",userVo.getRealname());
        }
        if(StringUtils.hasText(userVo.getBeginDate())){
            wrapper.ge("gmt_create",userVo.getBeginDate());
        }
        if(StringUtils.hasText(userVo.getEndDate())){
            wrapper.le("gmt_create",userVo.getEndDate());
        }
        Page<User> users = userMapper.selectPage(page, wrapper);

        // List<User>  users  = userMapper.findInfo(page, wrapper);

        long total = page.getTotal();
        Map<String,Object> map = new HashMap<>();
        map.put("users",users);
        map.put("tolal",total);
        if(page != null){
            return new CommonResult(2000,"分页查找用户信息成功",map);
        }
        return new CommonResult(5000,"分页查找用户信息失败",null);
    }

    /**
     * 添加商户
     * @param user
     * @return
     */
    @Override
    public CommonResult insertUser(User user) {
        System.out.println("/////////");
        String username = PasswordConfig.getRandomCharacters(8);
        String salt = PasswordConfig.getRandomCharacters(3);
        Md5Hash md5Hash =new Md5Hash("123456",salt,1024);
        user.setUsername(username);
        user.setPassword(md5Hash.toString());
        user.setSalt(salt);
        int insert = userMapper.insert(user);
        String id = user.getId();
        Map <String,Object> map =  new HashMap<>();
        map.put("roleid",1);
        map.put("userid",id);
        map.put("is_deleted",0);
        map.put("gmt_create",LocalDateTime.now());
        int i = userMapper.insertUserByRole(map);
        if(i>0 && insert>0){
            return new CommonResult(2000,"增加管理员成功，初始密码为123456",null);
        }
        return new CommonResult(5000,"增加管理员失败",null);
    }

    @Override
    public CommonResult updateUser(User user) {
        int update = userMapper.updateById(user);

        if(update>0 ){
            return new CommonResult(2000,"修改用户信息成功",null);
        }

        return new CommonResult(5000,"修改用户信息失败",null);
    }

    @Override
    public CommonResult deleteUser(String id) {
        User user = userMapper.selectById(id);
        user.setGmtModiffed(LocalDateTime.now());
        int update = userMapper.updateById(user);
        int i = userMapper.deleteById(id);

        if(i>0){
            return new CommonResult(2000,"删除用户成功",null);
        }
        return new CommonResult(5000,"删除用户失败",null);
    }

    /**
     * 小程序用户登录判断roleid
     * @param username
     * @return
     */
    @Override
    public Integer yonghuLogin(String username) {
        Integer integer = userMapper.yonghuLogin(username);
        return integer;
    }

    /**
     * 小程序端根据手机号登录
     * @param tel
     * @return
     */
    @Override
    public User findUserByTel(String tel) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("tel",tel);
        User user = userMapper.selectOne(wrapper);
        return user;
    }

    /**
     * 新增商户
     * @param
     * @return
     */
    @Override
    public String selectShop(User user) {
        Md5Hash password= new Md5Hash(user.getPassword(),user.getSalt(),1024);
        user.setPassword(password.toString());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        int insert = userMapper.insert(user);
        User user2 = userMapper.selectOne(wrapper);
        String id = user2.getId();
        Map map = new HashMap();
        map.put("roleid",2);
        map.put("userid",id);
        map.put("is_deleted",0);
        map.put("gmt_create",LocalDateTime.now());
        int i = userMapper.insertUserByRole(map);
        return id;
    }

    @Override
    public CommonResult findUsername() {
        QueryWrapper<User> wrapper= new QueryWrapper<>();
        wrapper.select("realname");
        List<User> users = userMapper.selectList(wrapper);
        if(users !=null){
            return new CommonResult(2000,"查找用户真实姓名成功",users);
        }
        return new CommonResult(5000,"查找用户真实姓名失败",null);
    }

    /**
     * 修改密码
     * @param request
     * @param map
     * @return
     */
    @Override
    public CommonResult updatePassword(HttpServletRequest request,Map map) {
        String token = request.getHeader("token");
        String s = redisTemplate.opsForValue().get(token);
        Map map2 = JSON.parseObject(s, Map.class);
        System.out.println(map);
        System.out.println("66666666666666666666");
        //从redis里面取出当前登录者的id值，第一次for循环遍历为了拿到user对象，第二次for循环遍历为了拿到id
        Map maps = (Map) JSON.parse(s);
        System.out.println(maps);
        String id=null;
        for (Object map1 : maps.entrySet()) {
            if ("user".equals(((Map.Entry) map1).getKey())){
                String value = ((Map.Entry) map1).getValue().toString();
                Map mapValue = (Map) JSON.parse(value);
                for (Object mapUser : mapValue.entrySet()) {
                    if ("id".equals(((Map.Entry) mapUser).getKey())){
                      id = (String) ((Map.Entry) mapUser).getValue();
                    }
                }
            }
        }
        System.out.println(id);
        System.out.println("77777777777777");
        //获取盐
        String salt1 = userMapper.selectSalt(id);
        String password = (String) map.get("pass");

        String newPassword=String.valueOf(new Md5Hash(password,salt1,1024));
        System.out.println(newPassword);
        System.out.println("/////////////");
        Map m = new HashMap();
        m.put("id",id);
        m.put("password",newPassword);
        System.out.println(m);
        System.out.println("*************");
        int i = userMapper.updataPassword(m);
        if(i>0){
            return new CommonResult(2000,"修改密码成功",null);
        }
        return new CommonResult(5000,"修改密码失败",null);
    }

}
